<?php

namespace app\merchants\services;

use app\common\loader\ModelShop;
use app\common\loader\ModelVirtual;
use app\common\loader\Services;
use think\Exception;
use think\helper\Str;

/**
 * 门店管理
 */
class ShopService
{
    /**
     * @title 门店列表
     * @param array $options
     * @return array
     * @throws \think\Exception
     */
    public function getPage(array $options): array
    {
        if (empty($options['field'])) {
            $options['field'] = 'id,code,title,manager,mobile,province,city,country,address,sales_man_num,status,op_user,status,create_at';
        }
        if (empty($options['order'])) {
            $options['order'] = 'create_at desc';
        }
        $list = ModelShop::Shop()->page($options);
        if (empty($list['data'])){
            return  $list;
        }
        $sales_man_num = ModelShop::ShopSalesman()->group('shop_id')
            ->column(null,'count(id) as sales_man_num','shop_id');
        foreach ($list['data'] as &$v){
            $v['sales_man_num'] = $sales_man_num[$v['id']] ?? 0;
        }
        Services::Helper()->showListTitle($list['data'], ['merchant' => 'op_user']);
        $this->showShopTags($list['data']);
        return $list;
    }

    /**
     * @title 门店列表
     * @param array $options
     * @return array
     * @throws \think\Exception
     */
    public function getList(array $options): array
    {
        if (empty($options['field'])) {
            $options['field'] = 'id,title,manager,mobile,status';
        }
        $options['order'] = 'id desc';
        return ModelShop::Shop()->select($options);
    }

    /**
     * 编辑门店
     * @param $params
     * @return int|mixed|string
     * @throws \think\Exception
     */
    public function saveShop($params)
    {
        $model = ModelShop::Shop();
        try {

            if (empty($params['code'])) {
                $params['code'] = substr(time(), 2). Str::random(3, 1);
            }
            $model->startTrans();
            $id = $params['id'] ?? 0;
            unset($params['id']);
            $params['update_at'] = Dt()->format();
            $check = $model->checkMobile($params['mer_id'] ?? '', $params['mobile'] ?? '');
            if ($id) {
                $where[] = ['id', '<>', $id];
            }
            $where[] = ['mer_id', '=', $params['mer_id']];

            if ($model->removeOption()->where($where)->where('code', $params['code'])->count() >= 1) {
                api_exception(API_ERROR, '编码已存在');
            }

            if ($model->removeOption()->where($where)->where('title', $params['title'])->count() >= 1) {
                api_exception(API_ERROR, '门店已存在');
            }
            if (!empty($id)) {
                if (!empty($check) && $check != $id) {
                    api_exception(400, '手机号已存在');
                }
                $model->removeOption()->where('id', $id)->update([], $params);
            } else {
                if (!empty($check)) {
                    api_exception(400, '手机号已存在');
                }
                $id = $model->insert($params, true);
            }
            if (isset($params['tags_id'])) {
                $this->bindShopTag($id, $params['tags_id'], $params['mer_id']);
            }
            $model->commit();
            return $id;
        } catch (Exception $e) {
            $model->rollback();
            throw $e;
        }
    }

    /**
     * @title 删除门店
     * @param array $where
     * @return bool
     * @throws Exception
     */
    public function delShop(array $where): bool
    {
        if (empty($where)) {
            return true;
        }
        $info = $this->getInfo(['where' => $where]);
        if (ModelShop::ShopSalesman()->where(['shop_id' => $info['id']])->count('id')) {
            throw  new Exception('导购已绑定该门店', API_ERROR);
        }
        $model = ModelShop::Shop();
        $model->startTrans();
        try {
            ModelShop::Shop()->removeOption()->delete(['id' => $info['id']]);
            ModelShop::ShopTagsBind()->delete(['shop_id' => $info['id']]);
            $model->commit();
            return true;
        } catch (Exception $e) {
            $model->rollback();
            throw $e;
        }

    }

    /**
     * @title 门店详情
     * @param array $options
     * @return array
     * @throws \think\Exception
     */
    public function getInfo(array $options): array
    {
        $info = ModelShop::Shop()->find($options);
        if (empty($info)) {
            api_exception(400, '门店不存在或已删除，请刷新后重试');
        }
        $info['tags_id'] = ModelShop::ShopTagsBind()->where('shop_id', $info['id'])->column('tags_id');
        return $info;
    }

    /**
     * @title 门店标签列表
     * @param array $options
     * @return array
     * @throws \think\Exception
     */
    public function getShopTagPage(array $options): array
    {
        if (empty($options['field'])) {
            $options['field'] = 'id,title,sort,create_at';
        }
        if (empty($options['order'])) {
            $options['order'] = 'sort desc';
        }
        return ModelShop::ShopTags()->page($options);
    }

    /**
     * @title 门店标签列表
     * @param array $options
     * @return array
     * @throws \think\Exception
     */
    public function getShopTagList(array $options): array
    {
        if (empty($options['field'])) {
            $options['field'] = 'id,title';
        }
        if (empty($options['order'])) {
            $options['order'] = 'sort desc';
        }
        return ModelShop::ShopTags()->select($options);
    }

    /**
     * 编辑门店标签
     * @param $params
     * @return int|mixed|string
     * @throws \think\Exception
     */
    public function saveShopTag($params)
    {
        $id = $params['id'] ?? 0;
        unset($params['id']);
        $params['update_at'] = Dt()->format();
        $check = ModelShop::ShopTags()->checkTitle($params['mer_id'] ?? '', $params['title'] ?? '');
        if (!empty($id)) {
            if (!empty($check) && $check != $id) {
                api_exception(400, '标签名称已存在');
            }
            ModelShop::ShopTags()->where('id', $id)->update([], $params);
        } else {
            if (!empty($check)) {
                api_exception(400, '标签名称已存在');
            }
            $id = ModelShop::ShopTags()->insert($params, true);
        }
        return $id;
    }

    /**
     * @title 删除门店标签
     * @param array $where
     * @return bool
     * @throws Exception
     */
    public function delShopTags(array $where): bool
    {
        if (empty($where)) {
            return true;
        }
        try {
            $info = $this->getShopTagInfo(['where' => $where]);
            $bind = ModelShop::ShopTagsBind()->where(['tags_id' => $info['id']])->find();
            if (!empty($bind)) {
                api_exception(400, '改标签已绑定门店，请先解除绑定');
            }
            ModelShop::ShopTags()->removeOption()->delete(['id' => $info['id']]);
            return true;
        } catch (Exception $e) {
            throw $e;
        }
    }

    /**
     * @title 门店标签详情
     * @param array $options
     * @return array
     * @throws \think\Exception
     */
    public function getShopTagInfo(array $options): array
    {
        $info = ModelShop::ShopTags()->find($options);
        if (empty($info)) {
            api_exception(400, '门店标签不存在或已删除，请刷新后重试');
        }
        return $info;
    }

    /**
     * 绑定标签
     * @param int $shop_id 门店ID
     * @param array $tags_id 标签ID集合
     * @throws \think\db\exception\DbException
     */
    private function bindShopTag(int $shop_id, array $tags_id, string $mer_id): void
    {
        $bindmodel = ModelShop::ShopTagsBind();
        $bindmodel->delete(['shop_id' => $shop_id]);
        $tags = empty($tags_id) ? [] : ModelShop::ShopTags()->whereIn('id', $tags_id)->where('mer_id', $mer_id)->column(null, 'id');
        $shop_tags = [];
        foreach ($tags as $v) {
            $shop_tags[] = [
                'shop_id' => $shop_id,
                'tags_id' => $v,
            ];
        }
        if (!empty($shop_tags)) {
            $bindmodel->removeOption()->insertAll($shop_tags);
        }
    }

    /**
     * 获取门店所绑定的标签
     * @param $list
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    private function showShopTags(&$list)
    {
        if (!empty($list)) {
            $shop_id = array_column($list, 'id');
            $bind = ModelShop::ShopTagsBind()->whereIn('shop_id', $shop_id)->select();
            $tags_id = array_column($bind, 'tags_id');
            $tags = empty($tags_id) ? [] : ModelShop::ShopTags()->whereIn('id', $tags_id)->column(null, 'title', 'id');
            $shop_tags = [];
            foreach ($bind as $v) {
                $shop_tags[$v['shop_id']][] = $tags[$v['tags_id']] ?? '';
            }
            foreach ($list as &$v) {
                $shop_tag = $shop_tags[$v['id']] ?? [];
                $shop_tag = array_filter($shop_tag);
                $v['shop_tag'] = $shop_tag;
            }
        }
    }

    /**
     * 标签绑定门店
     * @param int $tags_id
     * @param array $shop_id
     * @param string $mer_id
     * @throws Exception
     */
    public function bindShopTags(int $tags_id, array $shop_id, string $mer_id): void
    {
        $this->getShopTagInfo(['where' => ['id' => $tags_id, 'mer_id' => $mer_id]]);
        $shop_ids = empty($shop_id) ? [] : ModelShop::Shop()->whereIn('id', $shop_id)->where('mer_id', $mer_id)->column(null, 'id');
        $bindmodel = ModelShop::ShopTagsBind();
        $bind_shop = $bindmodel->whereIn('shop_id', $shop_ids)->where('tags_id', $tags_id)->column(null, 'shop_id');
        $shop_tags = [];
        foreach ($shop_ids as $v) {
            if (in_array((int)$v, $bind_shop, true)) {
                continue;
            }
            $shop_tags[] = [
                'shop_id' => $v,
                'tags_id' => $tags_id,
            ];
        }
        if (!empty($shop_tags)) {
            $bindmodel->removeOption()->insertAll($shop_tags);
        }
    }

    public function save_status($where, $data): void
    {
//        if ((int)$data['status'] === 0){
//            $where_raw = "limit_way::jsonb @> '[{\"id\":" .  $where['id']  . "}]'";
//            $wheres = ['mer_id'  =>  $where['mer_id'], 'type' => 2];
//            $virtual =  ModelVirtual::VirtualPromoSpecial()->where($wheres)->whereRaw($where_raw)->count('id');
//            if ($virtual > 0){
//                throw new Exception('门店已在活动中无法禁用', API_ERROR);
//            }
//        }
        $data =   ModelShop::Shop()->where($where)->update(null,$data);
      if (!$data){
          throw  new Exception('保存失败', API_ERROR);
      }
    }
}
